package com.central.apps.handler;

import com.central.app.service.HandlerService;
import com.central.apps.common.constant.InventoryConstant;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class MaterialCodeRequisitionHandler extends LvBaseHandler {


    @Autowired
    private HandlerService handlerService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if ("submit".equals(flowNode.getId())) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select applicanum  from gq_macoapplica where id=" + id);
            Map<String, Object> map = bySql.get(0);
            String applicanum = MapUtils.getString(map, "applicanum");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_materappline where applicanum='" + applicanum + "'");
            if (CollectionUtils.isEmpty(bySql1)) {
                return "请添加物料编码申请行相关信息！";
            }

            //判断流程前，该申请单和别的发起审批的申请子表物料是否有重复的。
            
        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("kfgly")) {
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                String macoapplicaSql = "select applicanum from gq_macoapplica where id=" + id;
                List<Map<String, Object>> bySql = handlerService.findBySql(macoapplicaSql);
                if (bySql != null && bySql.size() > 0) {
                    Map<String, Object> map = bySql.get(0);
                    String applicanum = MapUtils.getString(map, "applicanum");
                    String materapplineSql = "select * from gq_materappline where applicanum='" + applicanum+"'";
                    List<Map<String, Object>> bySql1 = handlerService.findBySql(materapplineSql);
                    if (bySql1 != null && bySql1.size() > 0) {
                        for (Map<String, Object> stringObjectMap : bySql1) {
                           String subcatecode = MapUtils.getString(stringObjectMap, "subcatecode");//小类编码
                            String middlecode = MapUtils.getString(stringObjectMap, "middlecode");//中类编码
                            //物料编码前，增加固定的CD值
                            String categorycode = "CD"+MapUtils.getString(stringObjectMap, "categorycode");//大类编码
                            String catecodedesc = MapUtils.getString(stringObjectMap, "catecodedesc");
                            String middcodedesc = MapUtils.getString(stringObjectMap, "middcodedesc");
                            String subcatecodedesc = MapUtils.getString(stringObjectMap, "subcatecodedesc");
                            //查物料编号

                            Integer itemnum = InventoryConstant.ITEMNUM_INIT_IDX;
                            //String itemnumSql ="select SUBSTRING(itemnum,6) as itemnum from gq_materappline where itemnum like '"+categorycode+middlecode+subcatecode+"%'order by SUBSTRING(itemnum,6) desc limit 1";
                            String itemnumSql = "select SUBSTRING(itemnum,6) as itemnum from gq_item where itemnum like '" + categorycode + middlecode + subcatecode + "%'order by SUBSTRING(itemnum,6) desc limit 1";
                            List<Map<String, Object>> itemnumList = handlerService.findBySql(itemnumSql);
                            if (itemnumList != null && itemnumList.size() > 0) {
                                Map<String, Object> map1 = itemnumList.get(0);
                                String itemnum1 = MapUtils.getString(map1, "itemnum");
                                if (StringUtils.isNotBlank(itemnum1)) {
                                    String substring = itemnum1.substring(itemnum1.length() - 6);
                                    itemnum = Integer.parseInt(substring);
                                }
                            }
                            itemnum = itemnum + 1;
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append(categorycode + middlecode + subcatecode + itemnum);
                            Integer materId = MapUtils.getInteger(stringObjectMap, "id");
                            String updateMaterapplineSql = "update gq_materappline set itemnum =" + "'" + stringBuilder.toString() + "'" + " where id=" + materId;
                            handlerService.updateBySql(updateMaterapplineSql);
                            //往物料主数据插数据
                            HashMap<String, Object> insertMap = new HashMap<>();
                            insertMap.put("itemnum", stringBuilder.toString());
                            insertMap.put("createuser", MapUtils.getString(stringObjectMap, "createuser"));
                            insertMap.put("description", MapUtils.getString(stringObjectMap, "description"));
                            insertMap.put("createtime", new Date());
                            insertMap.put("status", "已启用");
                            insertMap.put("orgcode","01");
                            insertMap.put("taxrate","0.13");
                            insertMap.put("maxnum", categorycode.replace("CD",""));
                            insertMap.put("maxdesc", catecodedesc);
                            insertMap.put("mediumnum", middlecode);
                            insertMap.put("mediumdesc", middcodedesc);
                            insertMap.put("smallnum", subcatecode);
                            insertMap.put("smalldesc", subcatecodedesc);
                            insertMap.put("itemtype", MapUtils.getString(stringObjectMap, "itemtype"));
                            insertMap.put("unit", MapUtils.getString(stringObjectMap, "unit"));
                            insertMap.put("outunit", MapUtils.getString(stringObjectMap, "orderunit"));
                            insertMap.put("model", MapUtils.getString(stringObjectMap, "model"));
                            insertMap.put("specifications",MapUtils.getString(stringObjectMap,"specifications"));
                            insertMap.put("manufacturer", MapUtils.getString(stringObjectMap, "manufacturer"));
                            insertMap.put("supplier", MapUtils.getString(stringObjectMap, "advisupplier"));
                            insertMap.put("lifemoney", MapUtils.getString(stringObjectMap, "life"));
                            insertMap.put("spemodel", MapUtils.getString(stringObjectMap, "spemodel"));
                            insertMap.put("packform", MapUtils.getString(stringObjectMap, "packform"));
                            insertMap.put("maintechtors", MapUtils.getString(stringObjectMap, "maintechtors"));
                            insertMap.put("qualitygrade", MapUtils.getString(stringObjectMap, "qualitygrade"));
                            insertMap.put("stexecunical",MapUtils.getString(stringObjectMap,"stexecunical"));
                            insertMap.put("matergrade",MapUtils.getString(stringObjectMap,"matergrade"));
                            insertMap.put("surfacement",MapUtils.getString(stringObjectMap,"surfacement"));
                            insertMap.put("versionNo",MapUtils.getString(stringObjectMap,"versionNo"));
                            insertMap.put("materialtion",MapUtils.getString(stringObjectMap,"materialtion"));
                            insertMap.put("matetegory",MapUtils.getString(stringObjectMap,"matetegory"));
                            insertMap.put("iscost",MapUtils.getString(stringObjectMap,"iscost"));//是否费用
                            insertMap.put("pccdesc","材料费");
                            insertMap.put("pccid",8);
                            //物料类型串存数据
                            insertMap.put("materialtypestring",categorycode.replace("CD","")+middlecode+subcatecode);
                            //物料类型描述根据‘/’拼接
                            insertMap.put("materialtype",catecodedesc+"/"+middcodedesc+"/"+subcatecodedesc);
                            //插入主数据
                            Object gqItem = handlerService.insert("gq_item", insertMap);
                            //回显物料id
                            int itemId = Integer.parseInt(String.valueOf(gqItem));
                            handlerService.findBySql("update gq_materappline set itemid = " + itemId + " where id = " + materId);
                            //回显物料类型，大类，中类，小类使用了，就不能对类型进行操作了
                            handlerService.findBySql("update gq_itemtype set isitemtypeuser = '2' where maxnum = '" + MapUtils.getString(stringObjectMap, "categorycode") + "'");
                            handlerService.findBySql("update gq_medium set ismediumuser = '2' where maxnum = '" + MapUtils.getString(stringObjectMap, "categorycode") + "' and mediumnum = '" + middlecode + "'");
                            handlerService.findBySql("update gq_small set issmalluser = '2' where maxnum = '" + MapUtils.getString(stringObjectMap, "categorycode") + "' and mediumnum = '" + middlecode + "' and smallnum = '" + subcatecode + "'");
                        }
                    }
                }
            }
        }
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data,boolean isUpdate) throws Exception {
        //修改保存
        if ("gq_materappline".equals(objName) && isUpdate) {
            if(data.get("description")!=null&&data.get("model")!=null){
                String description = (String) data.get("description");
                String model = (String) data.get("model");
                String id = MapUtils.getString(data, "id");
                String spemodel = MapUtils.getString(data, "spemodel");//品牌
                String applicanum = MapUtils.getString(data, "applicanum");//物料编码申请编码
                String specifications = MapUtils.getString(data, "specifications");
                if (StringUtils.isEmpty(specifications)){
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_materappline where description = '" + description + "' and model = '" + model + "' and applicanum = '" + applicanum + "' and id not in ('"+id+"')");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        throw new ServiceException("物料名称为" + description + ",型号为" + model + "的物料编码申请数据已存在，请修改后再保存。");
                    }
                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_item where description = '" + description + "' and model = '" + model + "'");
                    if(CollectionUtils.isNotEmpty(bySql)){
                        throw new ServiceException("物料名称为" + description + ",型号为" + model + "的主数据已存在，请修改后再保存。");
                    }
                    //新加的逻辑  品牌和型号不能重复
                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where model = '" + model + "' and spemodel = '" + spemodel + "' and description='"+description+"'");
                    if(CollectionUtils.isNotEmpty(bySql2)){
                        throw new ServiceException("物料名称为"+description+",品牌为" + spemodel + ",型号为" + model + "的主数据已存在，请修改后再保存。");

                    }
               }else {
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_materappline where description = '" + description + "' and model = '" + model + "' and specifications='"+specifications+"' and applicanum = '" + applicanum + "' and id not in ('"+id+"')");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        throw new ServiceException("物料名称为" + description + ",型号为" + model + ",规格为"+specifications+"的物料编码申请数据已存在，请修改后再保存。");
                    }
                    List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_item where description = '" + description + "' and model = '" + model + "' and specifications='"+specifications+"'");
                    if(CollectionUtils.isNotEmpty(bySql)){
                        throw new ServiceException("物料名称为" + description + ",型号为" + model + ",规格为"+specifications+"的主数据已存在，请修改后再保存。");
                    }
                    //新加的逻辑  品牌和型号不能重复
                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where model = '" + model + "' and spemodel = '" + spemodel + "' and description='"+description+"'");
                    if(CollectionUtils.isNotEmpty(bySql2)){
                        throw new ServiceException("物料名称为"+description+"品牌为" + spemodel + ",型号为" + model + "的主数据已存在，请修改后再保存。");
                    }
                }
            }
        }else if ("gq_materappline".equals(objName) && !isUpdate){
            //新增保存
            String description = (String) data.get("description");
            String model = (String) data.get("model");
            String spemodel = MapUtils.getString(data, "spemodel");//品牌
            String applicanum = MapUtils.getString(data, "applicanum");//物料编码申请编码
            String specifications = MapUtils.getString(data, "specifications");
            if (StringUtils.isEmpty(specifications)){
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_materappline where description = '" + description + "' and model = '" + model + "' and applicanum = '" + applicanum + "'");
                if(CollectionUtils.isNotEmpty(bySql1)){
                    throw new ServiceException("物料名称为" + description + ",型号为" + model + "的物料编码申请数据已存在，请修改后再保存。");
                }
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_item where description = '" + description + "' and model = '" + model + "'");
                if(CollectionUtils.isNotEmpty(bySql)){
                    throw new ServiceException("物料名称为" + description + ",型号为" + model + "的主数据已存在，请修改后再保存。");
                }
                //新加的逻辑  品牌和型号不能重复
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where model = '" + model + "' and spemodel = '" + spemodel + "'");
                if(CollectionUtils.isNotEmpty(bySql2)){
                    throw new ServiceException("物料品牌" + spemodel + ",型号为" + model + "的主数据已存在，请修改后再保存。");

                }
            }else {
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_materappline where description = '" + description + "' and model = '" + model + "' and specifications='"+specifications+"' and applicanum = '" + applicanum + "'");
                if(CollectionUtils.isNotEmpty(bySql1)){
                    throw new ServiceException("物料名称为" + description + ",型号为" + model + ",规格为"+specifications+"的物料编码申请数据已存在，请修改后再保存。");
                }
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_item where description = '" + description + "' and model = '" + model + "' and specifications='"+specifications+"'");
                if(CollectionUtils.isNotEmpty(bySql)){
                    throw new ServiceException("物料名称为" + description + ",型号为" + model + ",规格为"+specifications+"的主数据已存在，请修改后再保存。");
                }
                //新加的逻辑  品牌和型号不能重复
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where model = '" + model + "' and spemodel = '" + spemodel + "'");
                if(CollectionUtils.isNotEmpty(bySql2)){
                    throw new ServiceException("物料品牌" + spemodel + ",型号为" + model + "的主数据已存在，请修改后再保存。");
                }
            }
        }
        super.beforSave(app, objName, data, isUpdate);
    }

    //保存前判断物料名称和规格型号是否在 物料主数据存在

//    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("gq_materappline".equals(objName)) {
//
//            if(data.get("description")!=null&&data.get("model")!=null){
//                String description = (String) data.get("description");
//                String model = (String) data.get("model");
////                int id = (Integer)data.get("id");
////                List<Map<String, Object>> list = handlerService.findBySql("select model,description from gq_item where id = "+id);
//                String sql = "select * from gq_item where model ='" + model + "' and description = '" + description + "'";
//                List<Map<String, Object>> res = handlerService.findBySql(sql);
//                if (CollectionUtils.isNotEmpty(res)) {
//                    throw new ServiceException("物料名称为" + description + ",规格型号为" + model + "的物料主数据已存在，请修改后再保存。");
//                }
//            }
//        }
//    }

    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //判断是否是人员表
            if ("gq_item".equals(objName)&&!isUpdate) {
                Integer itemnum = InventoryConstant.ITEMNUM_INIT_IDX;
                //物料编码前，增加固定的CD值
                String maxnum = "CD"+MapUtils.getString(data, "maxnum");//大类编码
                String smallnum = MapUtils.getString(data, "smallnum");//小类编码
                String mediumnum = MapUtils.getString(data, "mediumnum");//中类编码
                int id =  MapUtils.getInteger(data, "id");
                //String itemnumSql ="select SUBSTRING(itemnum,6) as itemnum from gq_materappline where itemnum like '"+categorycode+middlecode+subcatecode+"%'order by SUBSTRING(itemnum,6) desc limit 1";
                String itemnumSql = "select SUBSTRING(itemnum,6) as itemnum from gq_item where itemnum like '" + maxnum + mediumnum + smallnum + "%'order by SUBSTRING(itemnum,6) desc limit 1";
                List<Map<String, Object>> itemnumList = handlerService.findBySql(itemnumSql);
                if (itemnumList != null && itemnumList.size() > 0) {
                    Map<String, Object> map1 = itemnumList.get(0);
                    String itemnum1 = MapUtils.getString(map1, "itemnum");
                    if (StringUtils.isNotBlank(itemnum1)) {
                        String substring = itemnum1.substring(itemnum1.length() - 6);
                        itemnum = Integer.parseInt(substring);
                    }
                }
                itemnum = itemnum + 1;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(maxnum + mediumnum + smallnum + itemnum);
                String sql = "update gq_item set itemnum = '"+stringBuilder.toString()+"' where id = "+id;
                handlerService.updateBySql(sql);

            }
        }


}
